<template>
	<view class="detail-container">
		<!-- 商品图片 -->
		<image class="product-image" :src="product.image" mode="aspectFill"></image>
		
		<!-- 商品信息 -->
		<view class="product-info">
			<view class="price-box">
				<text class="price">¥{{ product.price }}</text>
			</view>
			<text class="title">{{ product.name }}</text>
			<text class="desc">{{ product.description }}</text>
		</view>
		
		<!-- 底部操作栏 -->
		<view class="bottom-bar">
			<view class="action-buttons">
				<view class="action-item" @tap="toggleCollect">
					<image :src="isCollected ? '/static/sc2.png' : '/static/sc1.png'" mode="aspectFit"></image>
					<text>收藏</text>
				</view>
			</view>
			<view class="buy-buttons">
				<button class="add-cart-btn" @tap="addToCart">加入购物车</button>
				<button class="buy-now-btn" @tap="buyNow">立即购买</button>
			</view>
		</view>
	</view>
</template>

<script>
import { ref, onMounted } from 'vue'

export default {
	setup() {
		const product = ref({})
		const isCollected = ref(false)
		
		// 切换收藏状态
		const toggleCollect = () => {
			const userInfo = uni.getStorageSync('userInfo')
			if (!userInfo) {
				return uni.showToast({
					title: '请先登录',
					icon: 'none'
				})
			}

			const userList = uni.getStorageSync('userList') || []
			const userIndex = userList.findIndex(item => item.uid === JSON.parse(userInfo).uid)
			
			if (userIndex > -1) {
				const user = userList[userIndex]
				const collection = user.collection || []
				
				if (isCollected.value) {
					// 取消收藏
					const index = collection.findIndex(item => item.id === product.value.id)
					if (index > -1) {
						collection.splice(index, 1)
					}
				} else {
					// 添加收藏
					collection.push(product.value)
				}
				
				user.collection = collection
				userList[userIndex] = user
				uni.setStorageSync('userList', userList)
				
				isCollected.value = !isCollected.value
				uni.showToast({
					title: isCollected.value ? '收藏成功' : '已取消收藏',
					icon: 'success'
				})
			}
		}
		
		// 加载商品数据
		const loadProduct = () => {
			const pages = getCurrentPages()
			const currentPage = pages[pages.length - 1]
			const options = currentPage.options
			
			if (options.id) {
				const products = uni.getStorageSync('products') || []
				const currentProduct = products.find(item => item.id === options.id)
				
				if (currentProduct) {
					product.value = currentProduct
					
					// 检查是否已收藏
					const userInfo = uni.getStorageSync('userInfo')
					if (userInfo) {
						const userList = uni.getStorageSync('userList') || []
						const user = userList.find(user => user.uid === JSON.parse(userInfo).uid)
						if (user && user.collection) {
							isCollected.value = user.collection.some(col => col.id === currentProduct.id)
						}
					}
				} else {
					uni.showToast({
						title: '商品不存在',
						icon: 'none'
					})
					setTimeout(() => {
						uni.navigateBack()
					}, 1500)
				}
			}
		}
		
		// 加入购物车
		const addToCart = () => {
			const userInfo = uni.getStorageSync('userInfo')
			if (!userInfo) {
				return uni.showToast({
					title: '请先登录',
					icon: 'none'
				})
			}

			const userList = uni.getStorageSync('userList') || []
			const userIndex = userList.findIndex(item => item.uid === JSON.parse(userInfo).uid)
			
			if (userIndex > -1) {
				const user = userList[userIndex]
				const cart = user.cart || []
				
				// 检查商品是否已在购物车中
				const existingItem = cart.find(item => item.id === product.value.id)
				
				if (existingItem) {
					existingItem.quantity += 1
				} else {
					cart.push({
						...product.value,
						quantity: 1
					})
				}
				
				user.cart = cart
				userList[userIndex] = user
				uni.setStorageSync('userList', userList)
				
				uni.showToast({
					title: '已加入购物车',
					icon: 'success'
				})
			}
		}
		
		// 立即购买
		const buyNow = () => {
			const userInfo = uni.getStorageSync('userInfo')
			if (!userInfo) {
				return uni.showToast({
					title: '请先登录',
					icon: 'none'
				})
			}

			// 获取用户信息
			const userList = uni.getStorageSync('userList') || []
			const currentUser = userList.find(item => item.uid === JSON.parse(userInfo).uid)
			
			if (!currentUser) {
				uni.showToast({
					title: '用户信息不存在',
					icon: 'none'
				})
				return
			}

			// 检查余额是否足够
			if (parseFloat(currentUser.balance) < product.value.price) {
				uni.showModal({
					title: '提示',
					content: '余额不足，是否去充值？',
					success: (res) => {
						if (res.confirm) {
							uni.navigateTo({
								url: '../money/money'
							})
						}
					}
				})
				return
			}

			// 确认购买
			uni.showModal({
				title: '确认购买',
				content: `商品：${product.value.name}\n价格：¥${product.value.price}`,
				success: (res) => {
					if (res.confirm) {
						// 扣除余额
						const userIndex = userList.findIndex(item => item.uid === JSON.parse(userInfo).uid)
						const newBalance = (parseFloat(currentUser.balance) - product.value.price).toFixed(2)
						userList[userIndex].balance = newBalance
						
						// 生成订单
						const order = {
							id: Date.now().toString(),
							items: [{
								productId: product.value.id,
								quantity: 1,
								price: parseFloat(product.value.price),
								name: product.value.name,
								image: product.value.image,
								totalPrice: parseFloat(product.value.price)
							}],
							totalAmount: parseFloat(product.value.price),
							orderTime: new Date().toISOString(),
							status: 'paid',
							address: currentUser.address || '',
							phone: currentUser.phone || '',
							receiver: currentUser.receiver || ''
						}
						
						// 保存订单
						const orders = currentUser.orders || []
						orders.unshift(order)
						userList[userIndex].orders = orders
						
						// 保存更新后的数据
						uni.setStorageSync('userList', userList)
						
						uni.showToast({
							title: '购买成功',
							icon: 'success'
						})
						
						// 延迟返回上一页
						setTimeout(() => {
							uni.navigateBack()
						}, 1500)
					}
				}
			})
		}
		
		onMounted(() => {
			loadProduct()
		})
		
		return {
			product,
			isCollected,
			toggleCollect,
			addToCart,
			buyNow
		}
	}
}
</script>

<style scoped>
.detail-container {
	min-height: 100vh;
	background-color: #f8f8f8;
	padding-bottom: 120rpx;
}

.product-image {
	width: 100%;
	height: 750rpx;
	background-color: #fff;
	transition: transform 0.3s;
}

.product-image:active {
	transform: scale(1.02);
}

.product-info {
	background-color: #fff;
	padding: 40rpx 30rpx;
	margin-top: 20rpx;
	border-radius: 20rpx 20rpx 0 0;
	box-shadow: 0 -4rpx 16rpx rgba(0, 0, 0, 0.05);
}

.price-box {
	display: flex;
	align-items: baseline;
	margin-bottom: 24rpx;
}

.price {
	font-size: 56rpx;
	color: #ff0000;
	font-weight: bold;
	text-shadow: 0 2rpx 4rpx rgba(255, 0, 0, 0.1);
}

.price::before {
	content: '¥';
	font-size: 36rpx;
}

.title {
	font-size: 36rpx;
	color: #333;
	font-weight: bold;
	margin-bottom: 20rpx;
	line-height: 1.4;
	display: block;
}

.desc {
	font-size: 28rpx;
	color: #666;
	line-height: 1.6;
	margin-bottom: 20rpx;
	display: block;
}

.bottom-bar {
	position: fixed;
	left: 0;
	right: 0;
	bottom: 0;
	height: 120rpx;
	background-color: #fff;
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 0 30rpx;
	box-shadow: 0 -4rpx 16rpx rgba(0, 0, 0, 0.05);
}

.action-buttons {
	display: flex;
	margin-right: 30rpx;
}

.action-item {
	display: flex;
	flex-direction: column;
	align-items: center;
	margin-right: 40rpx;
	transition: transform 0.3s;
}

.action-item:active {
	transform: scale(0.95);
}

.action-item image {
	width: 48rpx;
	height: 48rpx;
	margin-bottom: 8rpx;
}

.action-item text {
	font-size: 22rpx;
	color: #666;
}

.buy-buttons {
	flex: 1;
	display: flex;
	justify-content: flex-end;
	gap: 20rpx;
}

.add-cart-btn, .buy-now-btn {
	width: 220rpx;
	height: 80rpx;
	line-height: 80rpx;
	text-align: center;
	border-radius: 40rpx;
	font-size: 28rpx;
	font-weight: bold;
	transition: all 0.3s;
}

.add-cart-btn {
	background-color: #fff;
	color: #007AFF;
	border: 2rpx solid #007AFF;
	box-shadow: 0 4rpx 12rpx rgba(0, 122, 255, 0.1);
}

.buy-now-btn {
	background: linear-gradient(135deg, #007AFF, #00BFFF);
	color: #fff;
	box-shadow: 0 4rpx 12rpx rgba(0, 122, 255, 0.2);
}

.add-cart-btn:active, .buy-now-btn:active {
	transform: scale(0.98);
	opacity: 0.9;
}

/* 添加图片加载动画 */
@keyframes shimmer {
	0% {
		background-position: -200% 0;
	}
	100% {
		background-position: 200% 0;
	}
}

.product-image {
	background: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%);
	background-size: 200% 100%;
	animation: shimmer 1.5s infinite;
}

.product-image[src] {
	animation: none;
}
</style>